#include "clientHead/transfile.h"

int transFile(int netfd, train_chdata* filename){ 
    int fd=open(filename,O_RDWR);
    if(fd==-1){
        return fd;
    }
    order_train_t train_t;
    struct stat stat_file;
    fstat(fd,&stat_file);
    //send file size
    train_t.order_len=ORDER_ERROR;
    train_t.data_len=sizeof(stat_file.st_size);
    memcpy(train_t.train_data,&stat_file.st_size,train_t.data_len);
    send(netfd,&train_t,sizeof(TokenType_)+sizeof(int)+train_t.data_len,MSG_NOSIGNAL);
    if(stat_file.st_size<FILE_MAX_SIZE){
        char* p=(char*)mmap(NULL,stat_file.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
        if(p==MAP_FAILED){
            return -1;
        }
        off_t totalsize=0;
        while(totalsize<stat_file.st_size){
            if(stat_file.st_size-totalsize<4096){
                train_t.data_len=stat_file.st_size-totalsize;
            }else{
                train_t.data_len=4096;
            }
            send(netfd,&train_t.data_len,sizeof(train_t.data_len),MSG_NOSIGNAL);
            send(netfd,p+totalsize,train_t.data_len,MSG_NOSIGNAL);
            totalsize+=train_t.data_len;
        }
        //space train
        train_t.data_len=0;
        send(netfd,&train_t.data_len,sizeof(train_t.data_len),MSG_NOSIGNAL);
        munmap(p,stat_file.st_size);
        close(fd);
        return 0;
    }
    //sendfile(netfd,fd,NULL,stat_file.st_size);
    close(fd);
    return 0;
}


